package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableRowSorter;

public class Productos extends javax.swing.JInternalFrame {
    private boolean nuevo;
    private String id_bitacora;
    private JFileChooser selector;
    public Productos() {
        initComponents();
        this.setLocation(new Point(70,0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("productos.xls"));
        BloquearControles(true);
        BloquearTexto(true);
        Limpiar();
        jbtnBuscar.setVisible(false);
        jbtnModificar.setEnabled(false);
        jbtnEliminar.setEnabled(false);
        if(Conexion.bitacora) id_bitacora=Util.IniciarBitacora(this.getTitle());
    }
    private void BloquearControles(boolean estado){
        jtbtnHabilitarBusqueda.setSelected(false);
        jbtnNuevo.setEnabled(estado);
        jbtnGuardar.setEnabled(!estado);        
        jbtnCancelar.setEnabled(!estado);
    }
    private void BloquearTexto(boolean estado){
        jtfNombre.setEditable(!estado);
        jtfUnidadMedida.setEditable(!estado);
        jtaDetalle.setEditable(!estado);
        jtfCantidadMinima.setEditable(!estado);
        jcbDevolutivo.setEnabled(!estado);
    }
    private void Limpiar(){
        jtfId.setText(null);
        jtfNombre.setText(null);
        jtaDetalle.setText(null);
        jtfUnidadMedida.setText(null);
        jtfCantidadMinima.setText(null);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpProducto = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtfNombre = new javax.swing.JTextField();
        jtfId = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jtfUnidadMedida = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtaDetalle = new javax.swing.JTextArea();
        jpAccion = new javax.swing.JPanel();
        jbtnCancelar = new javax.swing.JButton();
        jbtnEliminar = new javax.swing.JButton();
        jbtnModificar = new javax.swing.JButton();
        jbtnGuardar = new javax.swing.JButton();
        jbtnNuevo = new javax.swing.JButton();
        jtbtnHabilitarBusqueda = new javax.swing.JToggleButton();
        jbtnBuscar = new javax.swing.JButton();
        jbtnExportar = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        jtfCantidadMinima = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblProductos = new javax.swing.JTable();
        jcbDevolutivo = new javax.swing.JCheckBox();

        setClosable(true);
        setMaximizable(true);
        setTitle("Administración de Productos");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/producto.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jpProducto.setBorder(javax.swing.BorderFactory.createTitledBorder("Producto"));

        jLabel1.setText("Nombre:");

        jtfNombre.setToolTipText("Nombre del Producto");

        jtfId.setEditable(false);

        jLabel10.setText("Código:");

        jLabel9.setText("Detalle:");

        jLabel6.setText("Unidad de Medida:");

        jtaDetalle.setColumns(20);
        jtaDetalle.setRows(5);
        jScrollPane3.setViewportView(jtaDetalle);

        jpAccion.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));

        jbtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_cancelar.png"))); // NOI18N
        jbtnCancelar.setToolTipText("Cancelar");
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jbtnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_eliminar.png"))); // NOI18N
        jbtnEliminar.setToolTipText("Eliminar");
        jbtnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnEliminarActionPerformed(evt);
            }
        });

        jbtnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_modificar.png"))); // NOI18N
        jbtnModificar.setToolTipText("Modificar");
        jbtnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnModificarActionPerformed(evt);
            }
        });

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.setToolTipText("Guardar");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        jbtnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_nuevo.png"))); // NOI18N
        jbtnNuevo.setToolTipText("Nuevo");
        jbtnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevoActionPerformed(evt);
            }
        });

        jtbtnHabilitarBusqueda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/habilitar_busqueda.png"))); // NOI18N
        jtbtnHabilitarBusqueda.setToolTipText("Habilitar Busqueda");
        jtbtnHabilitarBusqueda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtbtnHabilitarBusquedaActionPerformed(evt);
            }
        });

        jbtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_buscar.png"))); // NOI18N
        jbtnBuscar.setToolTipText("Buscar");
        jbtnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnBuscarActionPerformed(evt);
            }
        });

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpAccionLayout = new javax.swing.GroupLayout(jpAccion);
        jpAccion.setLayout(jpAccionLayout);
        jpAccionLayout.setHorizontalGroup(
            jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpAccionLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jtbtnHabilitarBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jpAccionLayout.setVerticalGroup(
            jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jtbtnHabilitarBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jLabel11.setText("Cantidad Mínima:");

        jtfCantidadMinima.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfCantidadMinimaKeyTyped(evt);
            }
        });

        jtblProductos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblProductosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtblProductos);

        jcbDevolutivo.setText("Es Devolutivo");
        jcbDevolutivo.setToolTipText("Indica si el producto es de carácter devolutivo.");

        javax.swing.GroupLayout jpProductoLayout = new javax.swing.GroupLayout(jpProducto);
        jpProducto.setLayout(jpProductoLayout);
        jpProductoLayout.setHorizontalGroup(
            jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpProductoLayout.createSequentialGroup()
                .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpProductoLayout.createSequentialGroup()
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpProductoLayout.createSequentialGroup()
                                .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jpProductoLayout.createSequentialGroup()
                                        .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(4, 4, 4)
                                        .addComponent(jtfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel9))
                                    .addGroup(jpProductoLayout.createSequentialGroup()
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jtfUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jtfCantidadMinima, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(jpProductoLayout.createSequentialGroup()
                                .addComponent(jcbDevolutivo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jpAccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(27, 27, 27)))
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpProductoLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 792, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jpProductoLayout.setVerticalGroup(
            jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpProductoLayout.createSequentialGroup()
                .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpProductoLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1)
                                .addComponent(jtfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel9))
                            .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel10)
                                .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jtfUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jtfCantidadMinima, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11))
                        .addGroup(jpProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpProductoLayout.createSequentialGroup()
                                .addGap(14, 14, 14)
                                .addComponent(jcbDevolutivo))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpProductoLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jpAccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private String getFiltro(){
        String filtro="";
        filtro=(jtfNombre.getText().length()>0?" WHERE p.nombre LIKE '"+Util.ComponerTexto(jtfNombre.getText())+"%'":"");
        filtro+=(!jtaDetalle.getText().equals("")?(!filtro.equals("")?" AND":" WHERE")+" i.detalle LIKE '"+Util.ComponerTexto(jtaDetalle.getText())+"%'":"");
        filtro+=(!jtfUnidadMedida.getText().equals("")?(!filtro.equals("")?" AND":" WHERE")+" i.unidad_medida LIKE '"+Util.ComponerTexto(jtfUnidadMedida.getText())+"%'":"");
        filtro+=(!jtfCantidadMinima.getText().equals("")?(!filtro.equals("")?" AND":" WHERE")+" i.cantidad_minima<="+jtfCantidadMinima.getText():"");
        filtro+=(jcbDevolutivo.isSelected()?(!filtro.equals("")?" AND":" WHERE")+" p.es_devolutivo='S'":"");
        return filtro;
    }
    private void CargarProducto(){
        Util.CargarTabla(jtblProductos,"SELECT i.id_inventario,p.nombre,i.unidad_medida,i.detalle,i.cantidad_minima,"
            +"(CASE WHEN p.es_devolutivo='S' THEN 'Si' ELSE 'No' END) FROM inventario i INNER JOIN producto p "
            +"ON i.id_producto=p.id_producto",new String[]{"ID","Nombre","Unidad Medida","Detalle","Cantidad Mínima","Devolutivo"});
        Util.AlinearColumnas(jtblProductos,SwingConstants.CENTER);
        Util.OcultarColumna(jtblProductos,0);
        jtblProductos.setRowSorter(new TableRowSorter<MyModeloTabla>((MyModeloTabla)jtblProductos.getModel()));
    }
    private void jbtnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevoActionPerformed
        BloquearControles(false);
        BloquearTexto(false);
        Limpiar();
        jtblProductos.clearSelection();
        jtblProductos.setEnabled(false);
        jbtnModificar.setEnabled(false);
        jbtnEliminar.setEnabled(false);
        nuevo=true;
    }//GEN-LAST:event_jbtnNuevoActionPerformed
    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        BloquearControles(true);
        BloquearTexto(true);
        if(jtfId.getText().equals(""))
            Limpiar();
        jbtnModificar.setEnabled(false);
        jbtnEliminar.setEnabled(false);
        jtblProductos.setEnabled(true);
    }//GEN-LAST:event_jbtnCancelarActionPerformed
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        if(ValidarCampos()){
            if(nuevo){
                Guardar();
                CargarProducto();
                Limpiar();
                jbtnModificar.setEnabled(false);
                jbtnEliminar.setEnabled(false);
                jtblProductos.setEnabled(true);
            }
            else{
                if(!jtfId.getText().equals("")){
                    Actualizar();
                    if(jtblProductos.getRowCount()>0)
                        CargarProducto();
                    Limpiar();
                    jbtnModificar.setEnabled(false);
                    jbtnEliminar.setEnabled(false);
                    jtblProductos.setEnabled(true);
                }
                else
                    JOptionPane.showMessageDialog(null,"Para actualizar un producto de inventario primero debe seleccionarse el producto y cargar su información","No ha seleccionado producto",JOptionPane.WARNING_MESSAGE);
            }
            BloquearControles(true);
            BloquearTexto(true);
        }
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    private void Guardar(){
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL AgregarInventario('"+Util.ComponerTexto(jtfNombre.getText())+"','"
                +(jcbDevolutivo.isSelected()?"S":"N")+"','"+Util.ComponerTexto(jtaDetalle.getText())+"','"+Util.ComponerTexto(jtfUnidadMedida.getText())
                +"',"+jtfCantidadMinima.getText()+");")){
                        if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Guardar Producto: "+Util.ComponerTexto(jtfNombre.getText()+" "+jtfUnidadMedida.getText()+" "+jtaDetalle.getText()));
                        JOptionPane.showMessageDialog(null,"¡Producto Agregado!","Producto",JOptionPane.INFORMATION_MESSAGE);
        }
        else
            JOptionPane.showMessageDialog(null,"¡Hubo un error al agregar el producto!","Producto",JOptionPane.ERROR_MESSAGE);
    }
    private void Actualizar(){
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL ModificarInventario("+jtfId.getText()+",'"+Util.ComponerTexto(jtfNombre.getText())
                +"','"+(jcbDevolutivo.isSelected()?"S":"N")+"','"+Util.ComponerTexto(jtaDetalle.getText())+"','"
                +Util.ComponerTexto(jtfUnidadMedida.getText())+"',"+jtfCantidadMinima.getText()+");")){
                        if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Modificar Producto: "+Util.ComponerTexto(jtfNombre.getText()+" "+jtfUnidadMedida.getText()+" "+jtaDetalle.getText()));
                        JOptionPane.showMessageDialog(null,"¡Producto Actualizado!","Producto",JOptionPane.INFORMATION_MESSAGE);
        }
        else
            JOptionPane.showMessageDialog(null,"¡Hubo un error al actualizar el producto!","Producto",JOptionPane.ERROR_MESSAGE);
    }
    private void Eliminar(String id){
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL EliminarInventario("+id+");")){
            if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Eliminar Producto: "+Util.ComponerTexto(jtfNombre.getText()+" "+jtfUnidadMedida.getText()+" "+jtaDetalle.getText()));
            JOptionPane.showMessageDialog(null,"¡Producto Eliminado!","Producto",JOptionPane.INFORMATION_MESSAGE);
            CargarProducto();
            Limpiar();
        }
        else
            JOptionPane.showMessageDialog(null,"¡Hubo un error al eliminar el producto!","Producto",JOptionPane.ERROR_MESSAGE);
    }
    private boolean ValidarCampos(){
        String msj=null;
        msj=(jtfNombre.getText().equals("")?"Falta ingresar el nombre":"");
        msj+=(jtfUnidadMedida.getText().equals("")?(msj.equals("")?"Falta ingresar la unidad de medida":", la unidad de medida"):"");
        msj+=(jtfCantidadMinima.getText().equals("")?(msj.equals("")?"Falta ingresar la cantidad mínima":", la cantidad mínima"):"");
        if(!msj.equals("")) JOptionPane.showMessageDialog(null,msj+".","Falta ingresar campos",JOptionPane.WARNING_MESSAGE);
        return msj.equals("");
    }
    private void jtfCantidadMinimaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCantidadMinimaKeyTyped
        if(!Util.esNumero(jtfCantidadMinima.getText()+evt.getKeyChar(),false))
            evt.consume();
    }//GEN-LAST:event_jtfCantidadMinimaKeyTyped
    private void jtbtnHabilitarBusquedaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtbtnHabilitarBusquedaActionPerformed
        if(jtbtnHabilitarBusqueda.isSelected()){
            BloquearTexto(false);
            jtbtnHabilitarBusqueda.setIcon(new ImageIcon(getClass().getResource("/Recursos/deshabilitar_busqueda.png")));
            jtbtnHabilitarBusqueda.setToolTipText("Deshabilitar Busqueda");
            jbtnBuscar.setVisible(true);
        }
        else{
            jtbtnHabilitarBusqueda.setIcon(new ImageIcon(getClass().getResource("/Recursos/habilitar_busqueda.png")));
            jtbtnHabilitarBusqueda.setToolTipText("Habilitar Busqueda");
            jbtnBuscar.setVisible(false);
        }
    }//GEN-LAST:event_jtbtnHabilitarBusquedaActionPerformed
    private void jbtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnBuscarActionPerformed
        Util.CargarTabla(jtblProductos,"SELECT i.id_inventario,p.nombre,i.unidad_medida,i.detalle,i.cantidad_minima,"
                +"(CASE WHEN p.es_devolutivo='S' THEN 'Si' ELSE 'No' END) FROM inventario i INNER JOIN producto p ON i.id_producto=p.id_producto "
                +getFiltro(),new String[]{"ID","Nombre","Unidad Medida","Detalle","Cantidad Mínima","Devolutivo"});
        Util.AlinearColumnas(jtblProductos,SwingConstants.CENTER);
        Util.OcultarColumna(jtblProductos,0);
        jtblProductos.setRowSorter(new TableRowSorter<MyModeloTabla>((MyModeloTabla)jtblProductos.getModel()));
    }//GEN-LAST:event_jbtnBuscarActionPerformed
    private void jbtnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnModificarActionPerformed
        BloquearControles(false);
        BloquearTexto(false);
        nuevo=false;
    }//GEN-LAST:event_jbtnModificarActionPerformed
    private void jbtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEliminarActionPerformed
        if(!jtfId.getText().equals("")){
            if(JOptionPane.showConfirmDialog(null,"¿Esta seguro de eliminar el producto del inventario y todo lo relacionado con el producto?","Eliminar Producto", JOptionPane.YES_NO_OPTION)==JOptionPane.OK_OPTION){
                Eliminar(jtfId.getText());
            }
        }
    }//GEN-LAST:event_jbtnEliminarActionPerformed
    private void jtblProductosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblProductosMouseClicked
        if(evt.getClickCount()==2 && !evt.isConsumed()){
            if(jtblProductos.getSelectedRow()>-1){
                CargarInventario(jtblProductos.getSelectedRow());
                jbtnModificar.setEnabled(true);
                jbtnEliminar.setEnabled(true);
            }
        }
    }//GEN-LAST:event_jtblProductosMouseClicked
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        if(Conexion.bitacora) Util.ClausurarBitacora(id_bitacora);
    }//GEN-LAST:event_formInternalFrameClosing

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblProductos.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarExcel(jtblProductos,archivo_excel,"Productos")){
                        case OK:
                        JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                        Desktop.getDesktop().open(archivo_excel);
                        break;
                        case CANCELADO:
                        break;
                        case ERROR:
                        JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed
    private void CargarInventario(int fila){
        jtfId.setText(jtblProductos.getValueAt(fila,0).toString());
        jtfNombre.setText(jtblProductos.getValueAt(fila,1).toString());
        jtfUnidadMedida.setText(jtblProductos.getValueAt(fila,2).toString());
        jtaDetalle.setText(jtblProductos.getValueAt(fila,3).toString());
        jtfCantidadMinima.setText(jtblProductos.getValueAt(fila,4).toString());
        jcbDevolutivo.setSelected(jtblProductos.getValueAt(fila,5).toString().equals("Si"));
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbtnBuscar;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnEliminar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JButton jbtnModificar;
    private javax.swing.JButton jbtnNuevo;
    private javax.swing.JCheckBox jcbDevolutivo;
    private javax.swing.JPanel jpAccion;
    private javax.swing.JPanel jpProducto;
    private javax.swing.JTextArea jtaDetalle;
    private javax.swing.JTable jtblProductos;
    private javax.swing.JToggleButton jtbtnHabilitarBusqueda;
    private javax.swing.JTextField jtfCantidadMinima;
    private javax.swing.JTextField jtfId;
    private javax.swing.JTextField jtfNombre;
    private javax.swing.JTextField jtfUnidadMedida;
    // End of variables declaration//GEN-END:variables
}